package org.bozo.im.service.protocols.xmpp.stanza.processor.jabber.client;

import java.io.IOException;

import org.bozo.im.common.MessageType;
import org.bozo.im.common.types.Protocol;
import org.bozo.im.common.types.RawContact;
import org.bozo.im.service.IMService;
import org.bozo.im.service.core.roster.IMRoster;
import org.bozo.im.service.protocols.xmpp.XMPPSession;
import org.bozo.im.service.protocols.xmpp.stanza.Stanza;
import org.bozo.im.service.protocols.xmpp.stanza.processor.StanzaProcessor;
import org.bozo.im.service.protocols.xmpp.stanza.task.activity.UpdateContactsTask;
import org.bozo.im.service.protocols.xmpp.stanza.util.jabber.client.XMPPPresence;
import org.bozo.im.service.protocols.xmpp.util.jid.JID;
import org.bozo.im.service.protocols.xmpp.util.namespace.Namespace;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

public class PresenceStanzaProcessor extends StanzaProcessor {

	private static PresenceStanzaProcessor mInstance;

	private PresenceStanzaProcessor() {}

	public static PresenceStanzaProcessor getInstance() {
		if (mInstance == null)
			mInstance = new PresenceStanzaProcessor();
		return mInstance;
	}

	@Override
	public Stanza getStanza() {
		return Stanza.JABBER_CLIENT_PRESENCE;
	}

	@Override
	public void processStanza(XmlPullParser pParser, XMPPSession pSession, StanzaProcessor pParentProcessor) throws XmlPullParserException, IOException {

		String lCurrentName = getStanza().getName();

		Protocol lProtocol = pSession.getConfiguration().getProtocol();
		JID lFrom = null;
		XMPPPresence lPresence = XMPPPresence.CHAT;

		for (int i = 0; i < pParser.getAttributeCount(); i++) {
			if (pParser.getAttributeName(i).equals("from")) {
				lFrom = new JID(pParser.getAttributeValue(i));
			}
		}

		pParser.next();

		while (!(pParser.getEventType() == XmlPullParser.END_TAG && pParser.getName().equals(lCurrentName))) {

			if (pParser.getEventType() == XmlPullParser.START_TAG) {

				if (pParser.getName().equals("show") && pParser.getNamespace().equals(Namespace.JABBER_CLIENT.getNamespace())) {
					lPresence = XMPPPresence.valueOfPresence(pParser.nextText());
				}
			}

			pParser.next();
		}

		String lFromLoginName = lFrom.getLoginName();
		String lUserLoginName = pSession.getConfiguration().getLoginJID().getLoginName();
		
		if (!lFromLoginName.equals(lUserLoginName)) {
			IMRoster lRoster = IMService.getInstance().getRoster();
			RawContact lRawContact = lRoster.getContact(lProtocol, lFromLoginName);

			if (lPresence != null && lRawContact != null) {
				lRawContact.setPresence(lPresence.toCommonPresence());
				lRoster.itemModified(lRawContact, RawContact.Field.PRESENCE);
			}

			pSession.getTaskProcessor().pushTask(new UpdateContactsTask("contact-list-" + MessageType.GET_ROSTER_RESPONSE));
		}
	}

}
